﻿using Demo.Service;
using Demo.View;
using Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace Demo
{
    public partial class Main : Form
    {
        private UserService userService;
        public Main()
        {
            InitializeComponent();
            userService = new UserService();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex < 0)
            {
                return;
            }
            string operateType = dataGridView1.Columns[e.ColumnIndex].Name;
            int id = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
            if (operateType == "update")
            {
                UserDetail userDetail = new UserDetail();
                userDetail.SetUser(id);
                userDetail.Show();
            }
            else if (operateType == "del")
            {
                DialogResult result = MessageBox.Show("确认要删除"+ dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() + "？", "确认框",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    userService.Delete(id);
                    RefreshUserList();
                }
                else
                {
                }
                //MessageBox.Show("删除"+e.RowIndex);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            User user = new User();
            user.Name = textBox1.Text;
            user.Password = textBox2.Text;
            userService.Add(user);
            RefreshUserList();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            RefreshUserList();
        }

        private void RefreshUserList()
        {
            dataGridView1.Controls.Clear();
            List<User> userList = userService.List(txtSearchKeyword.Text);
            dataGridView1.RowCount = userList.Count;
            for (int i = 0; i < userList.Count; i++)
            {
                User user = userList[i];
                dataGridView1.Rows[i].Cells[0].Value = user.Id ;
                dataGridView1.Rows[i].Cells[1].Value = user.Name;
                dataGridView1.Rows[i].Cells[2].Value = user.Password;
            }
            //dataGridView1.DataSource = userList;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            RefreshUserList();
        }
    }
}
